package com.wedimob.slideshare.task.disk;

import java.net.URI;

import com.wedimob.slideshare.RuntimeConfig;
import com.wedimob.slideshare.WriteType;
import com.wedimob.slideshare.Writer;
import com.wedimob.slideshare.bo.SharedDocument;
import com.wedimob.slideshare.source.SlideShareStrategy;
import com.wedimob.slideshare.source.YoutubeStrategy;
import com.wedimob.slideshare.task.PoolExecutor;
import com.wedimob.slideshare.task.Task;
import com.wedimob.slideshare.task.TaskType;

public class TaskDocumentWriter extends Task<SharedDocument, SharedDocument> {

    private WriteType write;

    public TaskDocumentWriter(PoolExecutor pool, SharedDocument input, WriteType write, int timeout) {
        super(TaskType.DISK, pool, input, 0, timeout);
        this.write = write;
    }

    @Override
    public void run() {
        try {

            Writer writer = RuntimeConfig.getInstance().getWriter();
            if (accept(input.getSummary().getUrl(), SlideShareStrategy.URL_BASE)) {
                URI uri = PathHelper.buildTmpFile("index.html", input.getSummary().getAuthor(), input.getSummary()
                        .getTitle());

                StringBuilder sb = new StringBuilder();
                sb.append("<html>");
                sb.append("<body>");
                sb.append("<div>");
                sb.append("<a href='");
                sb.append(input.getSummary().getUrl());
                sb.append("'>");
                sb.append(input.getSummary().getTitle());
                sb.append("</a>");
                sb.append("</div>");
                for (int i = 1; i < input.getMedia().size(); i++) {
                    sb.append("<br/><img src='");
                    sb.append(input.getSummary().getPicture().getFilePath());
                    sb.append("'/>");
                }
                sb.append("</body>");
                sb.append("</html>");

                writer.write(sb.toString().getBytes(), uri);

                if (write != WriteType.NONE)
                    pool.execAsync(new TaskDocumentCBRWriter(pool, input, timeout));
            } else if (accept(input.getSummary().getUrl(), YoutubeStrategy.URL_BASE)) {
                /*
                writer.move(PathHelper.buildTmpPath(input.getSummary().getAuthor(), input.getSummary().getTitle()),
                        PathHelper.buildOutputPath(input.getSummary().getAuthor(), input.getSummary().getTitle()));
                        */
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.e = e;
        }
    }
}
